<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      <el-breadcrumb-item>角色详情</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddRoles">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="relolist" border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom',i1 === 0 ? 'bdtop' : '','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5" class="bdtop">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">
                  {{item1.authName}}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环 嵌套渲染二级权限 -->
                <el-row :class="[i2 === 0 ? '' : 'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3,i3) in item2.children" :key="item3.id" closable @close="removeRightById(scope.row,item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>


          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
             <el-button type="primary" icon="el-icon-edit"  size="mini"
             @click="showEditRoles(scope.row.id)">编辑</el-button>
             <!-- 删除按钮 -->
             <el-button type="danger" icon="el-icon-delete"  size="mini"
             @click="removeRolesById(scope.row.id)">删除</el-button>
             <!-- 分配角色按钮 -->
             <el-tooltip class="item" effect="dark" content="分配角色" placement="bottom" :enterable="false">
                 <el-button type="warning" icon="el-icon-setting"  size="mini" @click="showsetRightDialog(scope.row)">分配角色</el-button>
             </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="AddUserVisible"
      width="50%" @close="addFormClosed">
      <!-- 添加角色对话框主体 -->
      <el-form   label-width="70px" :rules="addFormRules" ref="addFormRef" :model="addForm">
        <el-form-item label="角色名称" >
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" >
          <el-input  v-model="addForm.roleDesc" required="true"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" >
        <el-button @click="AddUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="AddRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改按钮对话框 -->
    <el-dialog
      title="编辑角色信息"
      :visible.sync="RoleFormOC"
      width="50%">
      <el-form label-width="80px">
        <el-form-item label="角色ID">
          <el-input v-model="editForm.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
       <span slot="footer" class="dialog-footer">
        <el-button @click="RoleFormOC = false">取 消</el-button>
        <el-button type="primary" @click="ModifyRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="setRightDialog"
      width="50%"
      @close="setRightClose()">
      <!-- 树形控件 -->
     <el-tree :data="RightList" :props="treeProps" show-checkbox
     node-key="id" default-expand-all :default-checked-keys="defkeys"
     ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialog = false">取 消</el-button>
        <el-button type="primary" @click="allotRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default{
    data() {
      return {
        // 所有角色列表数据
        relolist:[],
        // 控制添加角色对话框
        AddUserVisible: false,
        // 添加角色输入框数据
        addForm: {
          roleName:'',
          roleDesc:'',
        },
        // 添加表单的验证规则
        addFormRules:{

        },
        // 添加表单的引用
        addFormRef:{
        },
        // 控制修改表单展示
        RoleFormOC: false,
        // 修改表单输入框数据
        editForm: {
          roleId:'',
          roleName:'',
          roleDesc:''
        },
        // 控制分配权限的对话框显示
        setRightDialog: false,
        //所有用户的权限列表
        RightList: [],
        // 树形控件的绑定对象
        treeProps: {
          label: 'authName',
          children: 'children'
        },
        // 默认选中的节点id值数组
        defkeys:[],
        // 当前分配权限角色id
        roleId: ''
       }
    },
    created() {
      this.goRolesList()
    },
    methods:{
      // 获取所有的角色列表数据
      goRolesList:async function(){
        const {data: res} = await this.$http.get('roles');
        if(res.meta.status !== 200){
          return this.$message.error('获取角色列表数据失败');
        }
        this.relolist = res.data;
        ;
      },
      // 监听添加角色按钮
      showAddRoles: function(){
        this.AddUserVisible = true;
      },
      // 添加角色表单确认按钮事件
      AddRole: async function(){
        if(this.addForm.roleName == ""){
          alert("角色名不能为空");
          return this.$message.error('添加角色失败')
        }
          const {data: res} = await this.$http.post('roles',this.addForm);
          if(res.meta.status !== 201){
            return this.$message.error('添加角色失败')
          }
            this.$message.success('角色添加成功');
            // 关闭对话框
            this.AddUserVisible = false;
            // 刷新角色列表
            this.goRolesList();
      },
      // 添加角色表单关闭事件
      addFormClosed: function(){
         this.$refs.addFormRef.resetFields();
      },
      // 监听修改按钮的点击事件
      showEditRoles: async function(id){
        console.log(id);
        const {data: res} = await this.$http.get('roles/'+id);
        console.log(res);
        if(res.meta.status !== 200){
          return this.$message.error('查询用户信息失败');
        }
        this.editForm = res.data;
        this.RoleFormOC = true;
      },
      // 修改角色表单的确认按钮
      ModifyRole: async function(){
        if(this.editForm.id == '' && this.editForm.roleName == ''){
          alert('id值和角色名字不能为空');
          this.$message.error('修改角色失败');
        }
        const {data: res} = await this.$http.put('roles/'+ this.editForm.roleId,
        {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc
        });
        if(res.meta.status !== 200){
          return this.$message.error('修改角色失败');
        }
        this.$message.success('修改角色信息成功');
        // 关闭对话框】
        this.RoleFormOC = false;
        // 重新刷新列表
        this.goRolesList();
      },
      // 删除角色表单确认按钮
      removeRolesById: async function(id){
          const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示',
                  {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).catch(err => err)
                  // 确认操作用户返回的是文本 confirm
                   console.log(confirmResult);
                  if(confirmResult == 'cancel'){
                    console.log(123);
                    return this.$message.info('已经取消删除');
                  }
                  const {data: res} = await this.$http.delete('roles/'+ id);
                  if(res.meta.status !== 200){
                    this.$message.error("删除角色失败")
                  }
                  this.$message.success("删除角色成功")
                  // 更新角色列表
                  this.goRolesList();
        },
      removeRightById: async function(role,rightid){
                  const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).catch(err =>err)

                  if(confirmResult !== 'confirm'){
                    return this.$message.info('取消了删除')
                  }
                  const{data: res} = await this.$http.delete(`roles/${role.id}/rights/${rightid}`);
                  if(res.meta.status !==200){
                    return this.$message.error('删除权限失败');
                  }
                  this.$message.success('删除权限成功了');
                  // 重新获取页面数据
                  role.children = res.data;
        },
        // 展示分配权限对话框
      showsetRightDialog: async function(role){
          this.roleId = role.id;
          // 获取所有的权限列表
          const {data: res} = await this.$http.get('rights/tree');
          // 使用递归获取三级节点id
          this.getLeafkeys(role,this.defkeys)
          this.setRightDialog = true;
          if(res.meta.status !== 200){
            return this.$message.error('获取用户列表失败');
          }
          this.RightList = res.data;
          console.log(this.RightList);
          console.log(this.defkeys)
        },
      // 通过递归的形式获取所有三级权限的id，并保存到defkeys中
      getLeafkeys: function(node,arr){
          // 如果节点没有children属性，就把id值添加到数组中
          if(!node.children){
            return arr.push(node.id)
          }
          node.children.forEach( item =>
          this.getLeafkeys(item,arr))
        },
      // 关闭分配权限对话框促发的事件
      setRightClose: function(){
        this.defkeys = [];
      },
      // 监听分配权限的确定按钮事件
      allotRights: async function(){
        console.log(1);
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        console.log(keys);
        const idstr = keys.join(',');
        console.log(idstr)
        const{data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids: idstr})
        if(res.meta.status !== 200){
          return this.$message.error('更新角色权限失败');
        }
        this.$message.success('分配权限成功');
        // 重新刷新数据列表
        this.goRolesList()
        // 关闭对话框
        this.setRightDialog = false;
      }
    }
  }
</script>

<style lang="less" scoped>
  .el-tag{
    margin: 7px;
  }
 .bdtop{
   border-top: 1px solid #eee;
 }
 .bdbottom{
   border-bottom: 1px solid #eee;
 }
 .vcenter{
   display: flex;
   align-items: center;
 }
</style>
